<?php
namespace App\Admin\Controllers;

use App\Admin\Filters\AdminRoleFilter;
use App\Admin\Models\AdminRole;
use App\Admin\Requests\AdminRoleRequest;
use App\Admin\Resources\AdminRoleResource;
use App\Admin\Models\AdminPermission;

class AdminRoleController extends Controller
{
    public function store(
        AdminRoleRequest $request, 
        AdminRole $adminRole
    ){
        $inputs = $request->validated();
        $adminRole = $adminRole->add($inputs);
        
        if (!empty($perms = $inputs['permissions'] ?? [])) {
            $adminRole->permissions()->attach($perms);
        }

        return $this->created(
            AdminRoleResource::make($adminRole)
        );
    }

    public function create()
    {
        $slugs = AdminPermission::$basicPermission;
        $result['data']['permissions'] = AdminPermission::whereIn('slug',$slugs)
            ->select(['id', 'name'])
            ->orderByDesc('id')
            ->get();
        return $this->ok(
            $result+$this->formData()
        );
    }

    public function update(
        AdminRoleRequest $request, 
        AdminRole $adminRole
    ){
        $inputs = $request->validated();
        $adminRole->update($inputs);

        if (isset($inputs['permissions'])) {
            $adminRole->permissions()->sync($inputs['permissions']);
        }

        return $this->created(
            AdminRoleResource::make($adminRole)
        );
    }

    public function edit(AdminRole $adminRole)
    {
        return $this->ok(
            AdminRoleResource::make($adminRole)
            ->for(AdminRoleResource::FOR_EDIT)
            ->additional($this->formData())
        );
    }
    
    public function destroy(
        AdminRole $adminRole
    ){
        $adminRole->delete();
        return $this->noContent();
    }

    public function index(
        AdminRoleFilter $filter,
    ){
        $adminRoles = AdminRole::withTrashed(isRestore())
            ->filter($filter)
            ->paginate();

        return $this->ok(
            AdminRoleResource::forCollection(
                AdminRoleResource::FOR_INDEX, $adminRoles
            )->additional($this->formData())
        );
    }


    public function show(
        Int $id
    ){
        $adminRole = AdminRole::withTrashed(isRestore())
            ->find($id);
        return $this->ok(
            AdminRoleResource::make($adminRole)
                ->for(AdminRoleResource::FOR_SHOW)
        );
    }

    /**
     * 返回添加和编辑表单所需的选项数据
     *
     * @return array
     */
    protected function formData()
    {
        $permissions = AdminPermission::query()
            ->select(['id', 'name'])
            ->orderByDesc('id')
            ->get();

        return compact('permissions');
    }
}
